package cn.v2tila.rsosa.management.service.serviceImpl;

import cn.v2tila.rsosa.management.entity.UserEntity;
import cn.v2tila.rsosa.management.jpa.UserJPA;
import cn.v2tila.rsosa.management.service.UserService;
import cn.v2tila.rsosa.management.utils.PageDataResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author v2tila on 18:24 2019/2/22
 */
@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory
            .getLogger(UserServiceImpl.class);

    @Autowired
    private UserJPA userJPA;

    public UserEntity findByOpenid(String openid) {

        return userJPA.findByOpenid(openid);
    }

    public UserEntity saveAndFlush(UserEntity userEntity) {

         return userJPA.saveAndFlush(userEntity);

    }


    public Page<UserEntity> findAll(Example<UserEntity> example, Pageable pageable){

        return userJPA.findAll(example, pageable);
    }

    @Override
    public PageDataResult getUsers(int page, int limit, UserEntity userEntity) {
        PageDataResult pageDataResult = new PageDataResult();
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        ExampleMatcher matcher;

        if(userEntity.getId()==0){
            matcher = ExampleMatcher.matching()
                    .withMatcher("uniqueId", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withIgnorePaths("id","isStu","isAsso");
        }else{
            matcher = ExampleMatcher.matching()
                    .withIgnorePaths("isStu","isAsso");
        }
        Example<UserEntity> example = Example.of(userEntity,matcher);
        Page<UserEntity> pages = userJPA.findAll(example,pageable);
        List<UserEntity> userEntityList = pages.getContent();
        int count = userJPA.findAll(example).size();
        pageDataResult.setData(userEntityList);
        pageDataResult.setCount(count);
        return pageDataResult;

    }

}
